﻿using System;
using System.Configuration;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Routing;
using System.Web.Mvc;
using MvcPaging;
using FeaturesBlog.Models;
using FeaturesBlog.Helpers;
using FeaturesBlog.Models.Interfaces;

namespace FeaturesBlog.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        public IDataManager DataManager { get; set; }

        protected override void Initialize(RequestContext requestContext)
        {
            if (DataManager == null) { DataManager = new DataManager(); }

            base.Initialize(requestContext);
        }
        //[OutputCache(VaryByParam="none", Duration=10)]
        public ActionResult Journal(int? page)
        {
            int currentPageIndex = page.HasValue ? page.Value - 1 : 0;

            IList<PostModel> pm = new List<PostModel>();
            foreach (Post p in DataManager.PostRepository.GetPosts(currentPageIndex, int.Parse(ConfigurationManager.AppSettings["JournalPageSize"])))
            {
                pm.Add(new PostModel { BlogPost = p, CommentsCount = DataManager.CommentsRepository.GetCommentCountByPostId(p.PostId), PostWithActions = true });
            }
            ViewData["PostsCount"] = DataManager.PostRepository.GetPostsCount();
            ViewData["CurrentPage"] = currentPageIndex + 1;
            
            return View(pm);
        }
        public ActionResult Index()
        {
            return RedirectToAction("Journal");
        }

        [Authorize]
        [ValidateInput(false)]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create(Post p)
        {
            if (ModelState.IsValid)
            {
                p.UserId = DataManager.UserRepository.GetUser(HttpContext.User.Identity.Name).UserId;
                p.Active = true;
                DataManager.PostRepository.AddPost(p);
                (new MailHelper()).SendNewPostNotification(p, DataManager.UserEmailRepository.GetAllEmails());
            }
            return RedirectToAction("Journal");
        }

        [Authorize]
        [ValidateInput(false)]
        public ActionResult Edit(decimal id)
        {
            Post p = DataManager.PostRepository.GetPost(id);
            ViewData.Model = p;
            return View();
        }
        [Authorize]
        [ValidateInput(false)]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Edit(decimal id, Post p)
        {
            if (ModelState.IsValid)
            {
                p.PostId = id;
                DataManager.PostRepository.EditPost(p);
            }
            return RedirectToAction("Journal");
        }

        [Authorize]
        public ActionResult Delete(int id)
        {
            DataManager.PostRepository.DeletePost(id);
            return RedirectToAction("Journal");
        }

        [Authorize]
        public ActionResult Create()
        {
            return View();
        }

        public ActionResult About()
        {
            return View();
        }

        public ActionResult Subscription()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Subscription(string email)
        {
            if (!MailHelper.ValidateEmail(email.ToLower()))
            {
                ModelState.AddModelError("", "The user email is incorrect.");
                return View();
            }
            UserEmail ue = new UserEmail();
            ue.Email = email.ToLower();
            DataManager.UserEmailRepository.AddEmail(ue);
            (new MailHelper()).SendConfirmNotification(ue);
            return RedirectToAction("Journal");
        }

        public ActionResult SubscriptionSuccess(string id)
        {
            decimal subscribeId = 0;
            try
            {
                subscribeId = SecurityHelper.IntDecode(id);
            }
            catch
            {
                ViewData["Result"] = "Failed!";
                return View();
            }
            UserEmail ue = DataManager.UserEmailRepository.GetEmail(subscribeId);
            if (ue != null)
            {
                ue.Active = true;
                DataManager.UserEmailRepository.EditEmail(ue);
                ViewData["Result"] = "Success!";
            }
            else
            {
                ViewData["Result"] = "Failed!";
            }
            return View();
        }

        public ActionResult ContentTable()
        {
            return PartialView(DataManager.PostRepository.GetPosts(0, int.Parse(ConfigurationManager.AppSettings["JournalPageSize"])));
        }
    }
}
